package com.company.LinkList;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}15:51
 */
public class BoyList {//单向环形链表
    private Boy first = null;

    public void add(int num){

        //辅助变量
        Boy curBoy = null;

        for (int i = 1; i <= num; i++ ){
            if (num < 1){
                System.out.println("人数必须大于等于一1");
                return;
            }else {
                Boy boy = new Boy(i);
                if (i == 1){//头节点赋值
                    first = boy;
                    first.next = first;//循环链表指向自己
                    curBoy = first;
                }else {
                    curBoy.next=boy;
                    boy.next=first;
                    curBoy = boy;//辅助变量后移
                }
            }
        }
    }

    //遍历环形链表
    public void showBoy(){
        if (first==null){
            System.out.println("没有任何数据");
            return;
        }else {
            Boy curBoy = first;
            while (true){
                System.out.println(curBoy.getNo());
                curBoy = curBoy.next;
                if (curBoy == first){
                    break;
                }
            }

        }

    }

    //约瑟夫环的执行模块
    public void outBoy(int startNo,int countNum, int nums){
        if (first == null || startNo < 1 || startNo > nums){
            System.out.println("输入参数有误");
            return;
        }

        Boy helper = first;
        //先将helper循环到最后的一个节点 方便之后的删除
        while (true){
            if (helper.next == first){
                break;
            }
            helper = helper.next;
        }
        //先将两个指针移动到开始的节点处
        for (int i = 0;i < startNo-1; i++){
            first = first.next;
            helper = helper.next;
        }

        //开始剔除
        while (true){
            if (first == helper){
                break;
            }
            //移动两个指针到特定的位置上
            for (int i = 0; i < countNum-1; i++){
                first = first.next;
                helper = helper.next;
            }
            //找到位置开始删除
            System.out.printf("被选中的节点为%d \n",first.getNo());
            first = first.next;
            helper.next = first;
        }
        System.out.printf("最后的一个节点为%d \n",first.getNo());
    }
}
